package com.zhuhanpeng.cloud.spring.security;

import com.zhuhanpeng.cloud.login.service.LoginService;
import com.zhuhanpeng.cloud.mybatis.entity.PtUserEntity;
import com.zhuhanpeng.cloud.spring.entity.GdmtUserEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service("userDetailsService")
public class GdmtUserDetailsService implements UserDetailsService {
    private Logger logger = LogManager.getLogger(this.getClass());
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private LoginAttemptService loginAttemptService;
    @Resource
    private LoginService loginService;
    @Override
    public UserDetails loadUserByUsername(String username ) throws UsernameNotFoundException {
        logger.info("userName:"+username);

      // String password = passwordEncoder.encode("123456");
        PtUserEntity ptUserEntity=loginService.queryUserInfoByName(username);
       if(ptUserEntity == null){
          throw new UsernameNotFoundException("userName:"+username);
       }

        logger.info(ptUserEntity);
        List<GrantedAuthority> collection = new ArrayList<>();
        List<String> list = loginService.queryAuthList(ptUserEntity.getUserUuid());
        for(String authString : list){
            collection.add(new SimpleGrantedAuthority("ROLE_" + authString));
        }
        GdmtUserEntity user = new  GdmtUserEntity(username, ptUserEntity.getPassword(),ptUserEntity,collection);
        if (loginAttemptService.isNeedCaptcha(username)) {
            logger.info("密码确实输错三次");
           ptUserEntity.setNeedCaptcha(true);
        }
        return user;
    }

    public void resetUserAttempt(String username) {
        loginAttemptService.resetUserAttempt(username);
    }

    public void loginSucceeded(String username) {
        loginAttemptService.loginSucceeded(username);
    }

    public void loginFailed(String username) {
        loginAttemptService.loginFailed(username);
    }
}
